<?php

declare (strict_types = 1);

namespace app\api\controller\v1;

use app\adminapi\controller\system\SysConfig;
use app\api\validate\UserValidate;
use app\common\controller\BaseController;
use app\common\exception\AdminException;
use app\common\repository\ad\RewardLogRepository;
use app\common\repository\user\UserRepository;
use app\common\repository\user\WithdrawalGearRepository;
use app\common\service\ad\RewardLogService;
use app\common\service\user\UserService;
use app\common\service\user\WithdrawalApplyService;
use app\common\service\user\WithdrawalGearService;
use app\common\service\wechat\WechatNotify;
use app\common\service\WeChatTransferService;
use think\Request;
use think\facade\Db;

class User extends BaseController
{
    protected Request $request;

    public function __construct(UserService $userService, Request $request)
    {
        $this->service = $userService;
        $this->request = $request;
        parent::__construct($userService);
    }

    /**
     * 获取用户信息
     *
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserInfo(): \think\Response
    {
        $user_id = $this->request->userInfo['user_id'];
        $arr = $this->service->getInfo($user_id)->toArray();
        $day_count = Db::name('reward_log')->where('user_id', $user_id)->whereDay('create_time')->count();
        $count = Db::name('reward_log')->where('user_id', $user_id)->count();
        return $this->success(array_merge($arr, [
            'day_count' => $day_count,
            'count'     => $count
        ]));
    }

    /**
     * 获取提现挡位
     * @return \think\Response
     */
    public function getGear(): \think\Response
    {
        $withdrawalGearService = app()->make(WithdrawalGearService::class);
        return $this->success($withdrawalGearService->getList());
    }

    /**
     * 提现
     *
     * @return \think\Response
     * @throws \Exception
     */
    public function Withdrawal(): \think\Response
    {
        $user_id = $this->request->userInfo['user_id'];
        $params = $this->getParams(['id'])['id'];
        $withdrawalApplyService = app()->make(WithdrawalApplyService::class);
        return $this->success($withdrawalApplyService->create($user_id, $params));
    }

    /**
     * 激励视频回调
     *
     * @return \think\Response
     */
    public function adCallback(): \think\Response
    {
        $data = $this->getParams();
        $data['platform'] = 1;
        return $this->success($this->service->adCallback($data));
    }

    /**
     * 激励视频回调IOS
     *
     * @return \think\Response
     */
    public function adCallbackIos(): \think\Response
    {
        $data = $this->getParams();
        $data['platform'] = 2;
        return $this->success($this->service->adCallback($data));
    }

    /**
     * 获取配置
     *
     * @return \think\Response
     */
    public function getConfig(): \think\Response
    {
        $params = $this->getParams(['name']);
        return $this->success(get_config('app.' . $params['name']));
    }

    /**
     * 通关
     *
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function pass(): \think\Response
    {
        $name = $this->getParams(['name'])['name'] ?? '';
        $user_id = $this->request->userInfo['user_id'];
        $res = Db::name('user_pass')->save([
            'user_id' => $user_id,
            'name' => $name,
            'create_time' => time(),
        ]);
//        $day_count = Db::name('user_pass')->whereDay('create_time')->count();
//        $day_task_number = get_config('app.day_task_number');
//        $reward_coins = get_config('app.reward_coins');
//        if($day_count == $day_task_number){
//            $userRep = app()->make(UserRepository::class);
//            $userRep->setInc([
//                'id' => $user_id,
//            ], 'balance', 'inc', (int)$reward_coins);
//        }
        return $this->success($res);
    }

    /**
     * 获取用户激励记录
     *
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     */
    public function getRewardLog(): \think\Response
    {
        $user_id = $this->request->userInfo['user_id'];
        $rewardLogService = app()->make(RewardLogService::class);
        return $this->success($rewardLogService->getList([
            'user_id' => $user_id,
        ]));
    }

    /**
     * 获取用户激励详情
     *
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     */
    public function getRewardInfo(): \think\Response
    {
        $transId = $this->request->param('trans_id');
        $rewardLogService = app()->make(RewardLogService::class);
        return $this->success($rewardLogService->getInfo([
            'trans_id' => $transId,
        ]));
    }

    /**
     * 是否为低价用户|是否超过今日观看次数或总次数
     *
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function isLowValueAdUser(): \think\Response
    {
        $user_id = $this->request->userInfo['user_id'];

        // 从配置中读取参数
        $thresholdCount = (int) get_config('app.low_price_num');           // 阈值次数，默认 3
        $thresholdAmount = (float) get_config('app.low_price_threshold'); // 低价金额阈值，默认 0.001
        $checkDays = (int) get_config('app.low_price_check_days');        // 检查最近 N 天，默认 3 天

        // 查询：最近 N 天内，该用户的激励视频收益记录（按时间倒序）
        $records = Db::name('reward_log')
            ->where('user_id', $user_id)
            ->where('create_time', '>=', date('Y-m-d H:i:s', strtotime("-{$checkDays} days")))
            ->order('create_time', 'DESC')
            ->limit($thresholdCount * 10) // 取多一点，避免刚好边界情况
            ->field(['coins, create_time', 'ecpm'])
            ->select()
            ->toArray();

        if (empty($records)) {
            // 无记录，默认不是低价用户
            return $this->success([
                'is_low_value' => false,
                'message' => '无收益记录',
                'low_count' => 0,
                'total_checked' => 0
            ]);
        }

        // 统计低于阈值的次数
        $lowCount = 0;
        foreach ($records as $record) {
            if ((float)$record['ecpm'] < $thresholdAmount) {
                $lowCount++;
            }
        }

        // 判断：是否达到“低价用户”标准
        $isLowValue = $lowCount >= $thresholdCount;

        return $this->success([
            'is_low_value' => $isLowValue,
            'message' => $isLowValue ? '该用户为低价广告用户' : '该用户非低价广告用户',
            'low_count' => $lowCount,                    // 低价次数
            'threshold_count' => $thresholdCount,        // 触发阈值
            'threshold_amount' => $thresholdAmount,      // 低价标准
            'check_days' => $checkDays,                  // 检查天数
            'total_checked' => count($records)           // 实际检查记录数
        ]);
    }

    /**
     * 提现回调
     *
     * @param $data
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function notify(): \think\Response
    {
        $transferService = app()->make(WechatNotify::class);
        $result = $transferService->handleTransfer();

        if ($result === 'FAIL') {
            // 处理失败
            return $this->notValidate('处理失败');
        }

        // 处理成功
        return $this->success($result);
    }

    /**
     * 获取用户提现列表
     *
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     */
    public function getUserWithdrawalApply(): \think\Response
    {
        $user_id = $this->request->userInfo['user_id'];
        return $this->success(app()->make(WithdrawalApplyService::class)->getList(['user_id' => $user_id]));
    }

    /**
     * 二次确认提现
     *
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function wechatTransfer(): \think\Response
    {
        $user_id = $this->request->userInfo['user_id'];
        $order_no = $this->getParams(['order_no'])['order_no'];
        return $this->success(app()->make(WithdrawalApplyService::class)->wechatTransfer($user_id, $order_no));
    }

    /**
     * 激励是否超出次数
     *
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function isExcitation(): \think\Response
    {
        $user_id = $this->request->userInfo['user_id'];
        $userInfo = Db::name('user')->where('id', $user_id)->find();
        $day_count = Db::name('reward_log')->where('user_id', $user_id)->whereDay('create_time')->count();
        $count = Db::name('reward_log')->where('user_id', $user_id)->count();

        if($day_count >= $userInfo['day_view_num'] && $userInfo['day_view_num'] != 0) {
            return $this->success(['success' => true]);
        }

        if($count >= $userInfo['max_view_num'] && $userInfo['max_view_num'] != 0) {
            return $this->success(['success' => true]);
        }

        return $this->success(['success' => false]);
    }
}